package com.gorkr.hot100.medium;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.Collectors;

import org.junit.Test;

/**
 * @author 张心宇 <zhangxinyu20@kuaishou.com>
 * Created on 2022-12-21
 */
public class M56MergerInterval {

    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0]-o2[0];
            }
        });
        ArrayList<int[]> res = new ArrayList<>();

        for (int i = 1; i < intervals.length; i++) {
            //
            if (intervals[i-1][1] >=intervals[i][0]) {

                intervals[i][0] = intervals[i-1][0];
                intervals[i][1] = Math.max(intervals[i-1][1], intervals[i][1]);
            }else {
                res.add(intervals[i-1]);
            }
        }
        // 判断最后一盒
        if(res.size()>0 && res.get(res.size()-1)[1] >=intervals[intervals.length-1][0]){
            res.get(res.size()-1)[1] = intervals[intervals.length-1][1];
        }else {
            res.add(intervals[intervals.length-1]);
        }

        int[][] ints = new int[res.size()][2];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = res.get(i);
        }
        return ints;
    }

    @Test
    public void test(){

        int[][] ints =  {{1,4},{4,5}};

        System.out.println(Arrays.deepToString(merge(ints)));
    }

}
